//
//  LDOauthViewController.swift
//  Weibo201655
//
//  Created by pro on 16/5/5.
//  Copyright © 2016年 LeeDan. All rights reserved.
//

import UIKit
import SVProgressHUD

class LDOauthViewController: UIViewController {
    
    override func loadView() {
        self.view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.whiteColor()
        //设置导航栏
        setupNavgationBar()
        //加载授权页面
        webView.loadRequest(NSURLRequest(URL: LDNetWorkTool.sharedNetWorkTool().oAuthURL()))

    }
    
    //MARK: 设置导航栏
    func setupNavgationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "loginFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "loginDismiss")
    }
    
    //MARK: 按钮点击
    func loginFill() {
        // 执行js代码,自动填充账号密码
        let js = "document.getElementById('userId').value='15576050540';document.getElementById('passwd').value='leedan'"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    func loginDismiss() {
        dismissViewControllerAnimated(true, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    //MARK: lazy
    lazy var webView: UIWebView = UIWebView()

}

extension LDOauthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showInfoWithStatus("正在加载。。。", maskType: SVProgressHUDMaskType.Black)
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
       // SVProgressHUD.showErrorWithStatus("加载失败，请重试")
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //http://itcast.cn/?code=36d140586d42034c607cecd60a115fc9
        let urlString = request.URL?.absoluteString
        //点击授权按钮后，判断是否是回调地址
        if urlString!.hasPrefix(LDNetWorkTool.sharedNetWorkTool().redirect_uri) {
           //?后面的参数
            let query = request.URL?.query
            //截取code
            let code = "code="
            if query!.hasPrefix(code) {
                //先转成OC字符串
                let queryStr = query! as NSString
                //再截取
                let codeStr = queryStr.substringFromIndex(code.characters.count)
                
                //发送请求，获取Token
                LDNetWorkTool.sharedNetWorkTool().loadAccessToken(codeStr, finished: { (response, error) -> () in
                    if response == nil || error != nil {
                        SVProgressHUD.showErrorWithStatus("网络加载不给力")
                        self.loginDismiss()
                        return
                    }
                    //创建用户，并保存到沙盒
                    sharedUserAccount = LDUserAccount(dict: response!)
                    sharedUserAccount!.saveUserAccount()
                    //用户头像。。。。
                    LDNetWorkTool.sharedNetWorkTool().loadMoreUserAccountInfo({ (response, error) -> () in
                        if response == nil || error != nil {
                            print(error)
                            SVProgressHUD.showErrorWithStatus("网络不给力")
                            return
                        }
                        
                        //完善用户信息
                        sharedUserAccount?.screen_name = response!["screen_name"] as? String
                        sharedUserAccount?.avatar_large = response!["avatar_large"] as? String
                        sharedUserAccount!.saveUserAccount()
                        
                        //登录成功，发送通知，切换控制器
                        NSNotificationCenter.defaultCenter().postNotificationName(LDSwitchRootViewControllerNotification, object: true)
                    })
                    
                })
            } else {
                //没有code，也要退出控制器
                SVProgressHUD.showErrorWithStatus("网络加载不给力")
                loginDismiss()
            }
            return false
        }
        // 2.不是授权回调地址,直接加载这个请求
        return true
    }
}
